package com.godme.concurrent.pattern;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkerThreadPattern {

    static class WorkerThread extends Thread {
        private final BlockingQueue<Runnable> tasks;

        public WorkerThread(String name,BlockingQueue<Runnable> tasks){
            super(name);
            this.tasks = tasks;
        }

        @Override
        public void run() {
            while (true){
                try {
                    tasks.take().run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        BlockingQueue<Runnable> tasks = new ArrayBlockingQueue<>(100);
        AtomicInteger counter = new AtomicInteger();
        new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                tasks.add(()-> {
                    System.err.println(Thread.currentThread().getName() + " : " + counter.getAndIncrement());
                });
                try {
                    Thread.sleep(300);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        for (int i = 0; i < 3; i++) {
            new WorkerThread("worker-"+i, tasks).start();
        }
    }
}
